# -*- coding: utf-8 -*-
# @Time    : 2022/10/10 22:17
# @Author  : 修远
# @File    : User.py
# @Comment : 
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
from app.app import db
from app.app import login_manager


class User(UserMixin, db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(255), nullable=False)
    _password = db.Column('password', db.String(255), nullable=False)
    email = db.Column(db.String(255), unique=True, nullable=False)
    logintime = db.Column(db.DateTime, default=datetime.now())

    __table_args__ = {
        "useexisting": True,
        "mysql_charset": "utf8"  # 重要点设置创建数据库的时候的字符集
    }

    @property  # 使用方法名来调用属性
    def password(self):
        return self._password

    @password.setter  # 设置密码，类似set方法
    def password(self, raw):
        self._password = generate_password_hash(raw)

    def check_password(self, raw):
        return check_password_hash(self._password, raw)


# 通过浏览器保存的users_id查询用户信息
@login_manager.user_loader
def get_user(userId):
    return User.query.get(int(userId))
